package cn.com.kh;

import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import javax.activation.MimetypesFileTypeMap;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

public class FileUtil {
    private static final Logger log = LoggerFactory.getLogger(FileUtil.class);

    /**
     * @param url         请求地址
     * @param fileParName fileKey
     * @param Files       post提交的文件列表
     * @param params      附带的文本参数
     * @param timeout     请求超时时间(毫秒)
     **/

    public static JSONObject HttpUploadFiles(String url, String fileParName, List<String> Files, Map<String, Object> params, int timeout) {
        JSONObject resultJson = new JSONObject();
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String result = "";
        try {
            HttpPost httpPost = new HttpPost(url);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            //设置请求的编码格式
            builder.setCharset(StandardCharsets.UTF_8);
            builder.setContentType(ContentType.MULTIPART_FORM_DATA);

            //设置浏览器兼容模式
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

            // 上传文件（多个）
            String fileName = null;
            MultipartFile multipartFile = null;
            for (String file : Files) {
                multipartFile = FileToMultipartFile(file);
                if (multipartFile == null) {
                    continue;
                }
                fileName = multipartFile.getName();
                builder.addBinaryBody(fileParName, multipartFile.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);// 文件流
            }

            //解决中文乱码
            ContentType contentType = ContentType.create("text/plain", "UTF-8");
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                System.out.println(entry.getValue());
                System.out.println(entry.getValue().toString());
                if (KHUtil.isNull(KHUtil.objIsNull(entry.getValue()) ? "" : entry.getValue().toString())) {
                    continue;
                } else {
                    // 类似浏览器表单提交，对应input的name和value
                    System.out.println(entry.getKey());
                    log.debug(entry.getKey(),entry.getValue().toString());
                    builder.addPart(entry.getKey(), new StringBody(entry.getValue().toString(), contentType));
                }
            }

            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost);// 执行提交

            // 设置连接超时时间
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build();
            httpPost.setConfig(requestConfig);

            HttpEntity responseEntity = response.getEntity();
            resultJson.put("code", response.getStatusLine().getStatusCode());
            resultJson.put("msg", "");
            if (responseEntity != null) {
                // 将响应内容转换为字符串
                result = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
                resultJson.put("msg", result);
            }
        } catch (Exception e) {
            resultJson.put("code", -1);
            resultJson.put("msg", "HTTP请求出现异常: " + e.getMessage());

            log.error("HTTP请求出现异常: ", e);
        } finally {
            //释放资源
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        log.debug("Upload Result:" + resultJson);
        return resultJson;
    }

    public static MultipartFile FileToMultipartFile(String filePath) {

        log.debug("文件路径：" + filePath);
        try {
            File file = new File(filePath);

            String mimeType = new MimetypesFileTypeMap().getContentType(file);
            log.debug("文件MimeType：" + mimeType);

            InputStream inputStream = new FileInputStream(file);

            MultipartFile multipartFile = new MockMultipartFile(file.getName(), file.getName(), mimeType, inputStream);
            log.debug("File转MultipartFile:" + multipartFile.getSize());

            return multipartFile;
        } catch (Exception e) {
            log.debug("File转MultipartFile异常:" + e.getMessage());
        }

        return null;
    }

}
